<?php
if (!defined('SHARE_VERSION')) exit('No direct script access allowed');
// +----------------------------------------------------------------------
// | 一起买好团
// +----------------------------------------------------------------------
// | Copyright (c) 2011 http://www.17mh.com All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: 吴锋(7462679@qq.com)
// +----------------------------------------------------------------------

// 公共函数库

/**
 +----------------------------------------------------------
 * __autoload 自动加载类文件
 +----------------------------------------------------------
 * @access public
 +----------------------------------------------------------
 * @param string $classname 类名
 +----------------------------------------------------------
 * @return boolean
 +----------------------------------------------------------
 */
function __autoload($className) {
	$classFile = '';
	if ( substr($className,-10)=='Controller' ) {
		$classFile = ROOT_PATH."Controller/".APP_NAME."/{$className}.php";
	} elseif(substr($classnames, -5)=='Model') {
		$classFile = ROOT_PATH."Model/".APP_NAME."/{$className}.php";
	} else {
		$classFile = SHARE_PATH."Lib/{$className}.class.php";
	}
	if ( !chkFile($classFile) ) {
		showError('类文件丢失', '类文件丢失。<br />类名：'.$className);
	}
	require_once($classFile);
}
/**
 +----------------------------------------------------------
 * replaceUrlStyle 过滤链接中相关参数
 +----------------------------------------------------------
 * @access public
 +----------------------------------------------------------
 * @param string str 字符
 +----------------------------------------------------------
 * @return none
 +----------------------------------------------------------
 */
function replaceUrlStyle($str){
	$str 	= trim($str);
	$str 	= str_replace(" ", "", $str);
	$str 	= strtolower($str);
	$str 	= ucwords($str);
	return $str;
}
/**
 +----------------------------------------------------------
 * chkAppDir 检测App目录
 +----------------------------------------------------------
 * @access public
 +----------------------------------------------------------
 * @param 
 +----------------------------------------------------------
 * @return 
 +----------------------------------------------------------
 */
 function chkAppDir(){
 	$appDir = ROOT_PATH.'Controller/'.APP_NAME;
 	if (!is_dir($appDir)) {
 		@mkdir($appDir, 0755);
 	}
 }
/**
 +----------------------------------------------------------
 * chkFile 检测文件
 +----------------------------------------------------------
 * @access public
 +----------------------------------------------------------
 * @param string $fileurl 文件地址
 +----------------------------------------------------------
 * @return string
 +----------------------------------------------------------
 */
function chkFile($fileUrl='') {
	if ( empty($fileUrl) ) {
		return false;
	}
	if ( !file_exists($fileUrl) ) {
		return false;
	}
	return true;
}
/**
 +----------------------------------------------------------
 * showError 基本错误
 +----------------------------------------------------------
 * @access public
 +----------------------------------------------------------
 * @param string $heading 标题
 * @param string $message 内容
 +----------------------------------------------------------
 * @return string
 +----------------------------------------------------------
 */
function showError($heading, $message) {
	require_once SHARE_PATH.'Errors/error_general.php';
	exit;
}
/**
 +----------------------------------------------------------
 * ass 为变量或者数组添加转义
 +----------------------------------------------------------
 * @access public
 +----------------------------------------------------------
 * @param array $value	转义内容
 +----------------------------------------------------------
 * @return array
 +----------------------------------------------------------
 */
function ass($value) {
	return $value = is_array($value) ? array_map('ass', $value) : addslashes($value);
}

/**
 +----------------------------------------------------------
 * getGpc 获取GPC变量。对于type为integer的变量强制转化为数字型
 +----------------------------------------------------------
 * @access public
 +----------------------------------------------------------
 * @param string $key	名称
 * @param string $type	integer 数值型;string 字符型;array 数组型
 * @param string $var	变量类型
 +----------------------------------------------------------
 * @return string	返回经过过滤或者初始化的变量
 +----------------------------------------------------------
 */
function getGpc($key, $type = 'integer', $var = 'P') {
	switch($var) 
	{
		case 'G': $var = &$_GET; break;
		case 'P': $var = &$_POST; break;
		case 'C': $var = &$_COOKIE; break;
		case 'R': $var = &$_REQUEST; break;
	}
	switch($type) {
		case 'integer':
			$return = isset($var[$key]) ? intval($var[$key]) : 0;
			break;
		case 'string':
			$return = isset($var[$key]) ? $var[$key] : NULL;
			break;
		case 'array':
			$return = isset($var[$key]) ? $var[$key] : array();
			break;
		default:
			$return = isset($var[$key]) ? intval($var[$key]) : 0;
	}
	return $return;
}
/**
 +----------------------------------------------------------
 * subMit 检查是否正确提交了表单
 +----------------------------------------------------------
 * @access public
 +----------------------------------------------------------
 * @param string $var 需要检查的变量
 * @param string $allowget 是否允许GET方式
 * @param string $seccodecheck 验证码检测是否开启
 +----------------------------------------------------------
 * @return 返回是否正确提交了表单
 +----------------------------------------------------------
 */
function subMit($var, $allowget = 0, $seccodecheck = 0)
{

	if(empty($GLOBALS['_REQUEST'][$var])){
		return false;
	} else {
		global $_SERVER;
		if($allowget || ($_SERVER['REQUEST_METHOD'] == 'POST' && (empty($_SERVER['HTTP_REFERER']) ||
			preg_replace("/https?:\/\/([^\:\/]+).*/i", "\\1", $_SERVER['HTTP_REFERER']) == preg_replace("/([^\:]+).*/", "\\1", $_SERVER['HTTP_HOST'])))){
			return true;
		} else {
			showError('submit_invalid', 'submit_invalid');
		}
	}
}

/**
 +----------------------------------------------------------
 * getHttp 协议
 +----------------------------------------------------------
 * @access public
 +----------------------------------------------------------
 * @param 
 +----------------------------------------------------------
 * @return string
 +----------------------------------------------------------
 */
function getHttp(){
	return (isset($_SERVER['HTTPS']) && (strtolower($_SERVER['HTTPS']) != 'off')) ? 'https://' : 'http://';
}
/**
 +----------------------------------------------------------
 * getDomain 取得当前域名
 +----------------------------------------------------------
 * @access public
 +----------------------------------------------------------
 * @param 
 +----------------------------------------------------------
 * @return string
 +----------------------------------------------------------
 */
function getDomain() {
	/* 域名或IP地址 */
	if (isset($_SERVER['HTTP_X_FORWARDED_HOST'])){
		$host = $_SERVER['HTTP_X_FORWARDED_HOST'];
	} elseif (isset($_SERVER['HTTP_HOST'])) {
		$host = $_SERVER['HTTP_HOST'];
	} else {
		/* 端口 */
		if (isset($_SERVER['SERVER_PORT'])) {
			$port = ':' . $_SERVER['SERVER_PORT'];
			if ((':80' == $port && 'http://' == $protocol) || (':443' == $port && 'https://' == $protocol)){
				$port = '';
			}
		} else {
			$port = '';
		}
		if (isset($_SERVER['SERVER_NAME'])){
			$host = $_SERVER['SERVER_NAME'] . $port;
		} elseif (isset($_SERVER['SERVER_ADDR'])) {
			$host = $_SERVER['SERVER_ADDR'] . $port;
		}
	}
	//return $protocol . $host;
	return $host;
}
/**
 +----------------------------------------------------------
 * getClientIp 获取客户端IP地址
 +----------------------------------------------------------
 * @access public
 +----------------------------------------------------------
 * @param 
 +----------------------------------------------------------
 * @return string
 +----------------------------------------------------------
 */
function getClientIp(){
	if (getenv("HTTP_CLIENT_IP") && strcasecmp(getenv("HTTP_CLIENT_IP"), "unknown")) {
		$ip = getenv("HTTP_CLIENT_IP");
	} elseif (getenv("HTTP_X_FORWARDED_FOR") && strcasecmp(getenv("HTTP_X_FORWARDED_FOR"), "unknown")) {
		$ip = getenv("HTTP_X_FORWARDED_FOR");
	} elseif (getenv("REMOTE_ADDR") && strcasecmp(getenv("REMOTE_ADDR"), "unknown")) {
		$ip = getenv("REMOTE_ADDR");
	} elseif (isset($_SERVER['REMOTE_ADDR']) && $_SERVER['REMOTE_ADDR'] && strcasecmp($_SERVER['REMOTE_ADDR'], "unknown")) {
		$ip = $_SERVER['REMOTE_ADDR'];
	} else {
		$ip = "unknown";
	}
	return($ip);
}
/**
 +----------------------------------------------------------
 * Redirect URL重定向
 +----------------------------------------------------------
 * @access public
 +----------------------------------------------------------
 * @param string url 跳转地址
 * @param int time 跳转时间
 * @param string  msg 显示内容
 +----------------------------------------------------------
 * @return string
 +----------------------------------------------------------
 */
function Redirect($url='',$time=0,$msg='') {
	if ( empty($url) ){
		$url = $_SERVER['HTTP_REFERER'];
	}
	if(empty($msg))
		$msg    =   "系统将在{$time}秒之后自动跳转到{$url}！";
	if (!headers_sent()) {
		// redirect
		if(0===$time) {
			header("Location: ".$url);
		}else {
			header("refresh:{$time};url={$url}");
			echo($msg);
		}
		exit();
	}else {
		$str    = "<meta http-equiv='Refresh' content='{$time};URL={$url}'>";
		if($time!=0)
			$str   .=   $msg;
		exit($str);
	}
}
/**
 +----------------------------------------------------------
 * U url链接
 +----------------------------------------------------------
 * @access public
 +----------------------------------------------------------
 * @param string $param 需要转换的字符串
 +----------------------------------------------------------
 * @return string
 +----------------------------------------------------------
 */
function U($param) {
	$param	= trim($param);
	if (empty($param)) {
		return;
	}
	if ($param == '@') {
		// 回项目首页
		return '/';
	}
	$url_array   	 = explode("?", $param);
	$act_str     	 = $url_array[0];
	$a_array     	 = explode("/", $act_str);
	$controller  	 = $a_array[0];
	if (empty($a_array[1])) {
		$operate 	 = 'index';
	} else {
		$operate 	 = $a_array[1];
	}
	$url = '';
	$url .= "?c={$controller}&a={$operate}";
	if (false !== strpos($param, "?")) {
		// 有其它参数
		$param_str	= $url_array[1];
		$url 		.= "&".$param_str;
	}
	return $url;
}
if (!function_exists('json_encode')) {
	 function format_json_value(&$value)
	{
		if(is_bool($value)) {
			$value = $value?'true':'false';
		}elseif(is_int($value)) {
			$value = intval($value);
		}elseif(is_float($value)) {
			$value = floatval($value);
		}elseif(defined($value) && $value === null) {
			$value = strval(constant($value));
		}elseif(is_string($value)) {
			$value = '"'.addslashes($value).'"';
		}
		return $value;
	}

	function json_encode($data)
	{
		if(is_object($data)) {
			//对象转换成数组
			$data = get_object_vars($data);
		}else if(!is_array($data)) {
			// 普通格式直接输出
			return format_json_value($data);
		}
		// 判断是否关联数组
		if(empty($data) || is_numeric(implode('',array_keys($data)))) {
			$assoc  =  false;
		}else {
			$assoc  =  true;
		}
		// 组装 Json字符串
		$json = $assoc ? '{' : '[' ;
		foreach($data as $key=>$val) {
			if(!is_null($val)) {
				if($assoc) {
					$json .= "\"$key\":".json_encode($val).",";
				}else {
					$json .= json_encode($val).",";
				}
			}
		}
		if(strlen($json)>1) {// 加上判断 防止空数组
			$json  = substr($json,0,-1);
		}
		$json .= $assoc ? '}' : ']' ;
		return $json;
	}
}
if (!function_exists('json_decode')) {
	function json_decode($json,$assoc=false)
	{
		// 目前不支持二维数组或对象
		$begin  =  substr($json,0,1) ;
		if(!in_array($begin,array('{','[')))
			// 不是对象或者数组直接返回
			return $json;
		$parse = substr($json,1,-1);
		$data  = explode(',',$parse);
		if($begin =='{' ) {
			// 转换成PHP对象
			$result   = new stdClass();
			foreach($data as $val) {
				$item    = explode(':',$val);
				$key =  substr($item[0],1,-1);
				$result->$key = json_decode($item[1],$assoc);
			}
			if($assoc)
				$result   = get_object_vars($result);
		}else {
			// 转换成PHP数组
			$result   = array();
			foreach($data as $val)
				$result[]  =  json_decode($val,$assoc);
		}
		return $result;
	}
}
/**
 +----------------------------------------------------------
 * 把返回的数据集转换成Tree
 +----------------------------------------------------------
 * @access public
 +----------------------------------------------------------
 * @param array $list 要转换的数据集
 * @param string $pid parent标记字段
 * @param string $level level标记字段
 +----------------------------------------------------------
 * @return array
 +----------------------------------------------------------
 */
function list_to_tree($list, $pk='id',$pid = 'pid',$child = '_child',$root=0){
	// 创建Tree
	$tree = array();
	if(is_array($list)){
		// 创建基于主键的数组引用
		$refer = array();
		foreach ($list as $key => $data){
			$refer[$data[$pk]] =& $list[$key];
		}
		foreach ($list as $key => $data){
			// 判断是否存在parent
			$parentId = $data[$pid];
			if ($root == $parentId){
				$tree[] =& $list[$key];
			}else{
				if (isset($refer[$parentId])){
					$parent =& $refer[$parentId];
					$parent[$child][] =& $list[$key];
				}
			}
		}
	}
	return $tree;
}
/**
 +----------------------------------------------------------
 * Debug 运行调试信息
 +----------------------------------------------------------
 * @access public
 +----------------------------------------------------------
 * @param 
 +----------------------------------------------------------
 * @return string
 +----------------------------------------------------------
 */
function Debug(){
	$run_time = (array_sum(explode(' ', microtime()))-$GLOBALS['_start_time_']);
	$str = '执行时间：'.round($run_time,10).'秒<br />';
	if (function_exists('memory_get_usage')) {
		$str .= '内存使用：'.number_format(memory_get_usage()).' 字节.<br>';
	}
	return $str;
}
?>